import React from 'react';
import type { Patient } from '@/type/PatientType';
import SvgIcon from '@/components/SvgIcon/SvgIcon';
import { deletePatient } from '@/store/modules/patientStore';
import { Dialog, Toast } from 'antd-mobile';
import { useEnhanceDispatch } from '@/hooks';
import './PatientItem.scss';
import classNames from 'classnames';


interface PatientItemProps {
  selected: 'Medicine' | 'Fast';
  patient: Patient;
  defaultPatient: Patient;
  success: () => void;
  handleEdit: (patientId: string) => void;
  setDefaultPatient: (patient: Patient) => void;
}

const PatientItem: React.FunctionComponent<PatientItemProps> = ({ selected, patient, defaultPatient, success, handleEdit, setDefaultPatient }) => {
  const enhanceDispatch = useEnhanceDispatch();

  /**
   * @description 删除就诊人的回调函数
   * */
  const handleDeletePatient = async () => {
    const confirm = await Dialog.confirm({ content: `确定删除${patient.name}吗?`, header: '温馨提示' });
    if (!confirm) return;
    try {
      const deleteMessage = await enhanceDispatch(deletePatient(patient.id as string)).unwrap();
      success();
      Toast.show({
        icon: 'success',
        content: deleteMessage,
      });
    } catch (rejectedValueOrSerializedError: any) {
      Toast.show(rejectedValueOrSerializedError);
    }
  };


  /**
   *@description 点击编辑就诊人
   * */
  const handleEditPatient = () => {
    handleEdit(patient.id as string);
  };

  /**
   * @description 选择就诊人的回调函数
   * */
  const selectedPatient = () => {
    if (selected !== 'Medicine' && selected !== 'Fast') return;
    setDefaultPatient(patient);
  };

  return (
    <div className={classNames('patient-item', defaultPatient?.id === patient.id && selected ? 'selected' : '')} onClick={selectedPatient}>
      <div className="info">
        <span className="name">{patient.name}</span>
        <span className="id">{patient.idCard.replace(/^(.{6}).+(.{4})$/, '\$1********\$2')}</span>
        <span>{patient.genderValue}</span>
        <span>{patient.age}岁</span>
      </div>
      <div className="icon" onClick={handleEditPatient}>
        <SvgIcon name="edit" width="20px" height="20px"></SvgIcon>
      </div>
      {patient.defaultFlag === 1 && <div className="tag">默认</div>}
      <div className="delete" onClick={handleDeletePatient}>
        <SvgIcon name="delete" width="20px" height="20px"></SvgIcon>
      </div>
    </div>
  );
};

export default PatientItem;